package com.study.zgw.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicInteger;
@Slf4j
public class MultiThreadServer {

    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8080));

        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT,null);

        Worker[] workers = new Worker[Runtime.getRuntime().availableProcessors()];
        for (int i = 0; i < workers.length; i++) {
            log.info("第{}个worker添加成功",i);
            workers[i] = new Worker("worker-"+i);
        }

        AtomicInteger index = new AtomicInteger();
        while (true){
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                iterator.remove();
                if (selectionKey.isAcceptable()) {
                    SocketChannel channel = ssc.accept();
                    channel.configureBlocking(false);
                    log.info(Thread.currentThread().getName()+"--slf4j-connect------->"+channel.getRemoteAddress());
                    //关联selector
                    System.out.println(Thread.currentThread().getName()+"---before register------->"+channel.getRemoteAddress());
                    //轮询
                    workers[index.getAndIncrement()%workers.length].register(channel);
                    System.out.println(Thread.currentThread().getName()+"---after register------>"+channel.getRemoteAddress());
                }
            }
        }
    }


    static class Worker implements Runnable{

        private Thread thread;
        private Selector selector;
        private String name;
        private volatile boolean start = false;

        private ConcurrentLinkedDeque<Runnable> queue = new ConcurrentLinkedDeque<>();

        public Worker(String name) {
            this.name = name;
        }

        //初始化线程 和 register
        public void register(SocketChannel channel) throws IOException {
            if (!start) {
                selector = Selector.open();
                thread = new Thread(this,name);
                thread.start();
                start = true;
            }
            queue.add(()->{
                try {
                    channel.register(selector,SelectionKey.OP_READ,null);
                } catch (ClosedChannelException e) {
                    throw new RuntimeException(e);
                }
            });
            selector.wakeup();//唤醒被阻塞的selector
        }

        @Override
        public void run() {
            while (true){
                try {
                    selector.select();
                    Runnable task = queue.poll();
                    if (task != null) {
                        task.run();
                    }
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        iterator.remove();
                        if (selectionKey.isReadable()) {
                            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                            SocketChannel channel = (SocketChannel) selectionKey.channel();
                            System.out.println(Thread.currentThread().getName()+"---read------->"+channel.getRemoteAddress());
                            try {
                                channel.read(byteBuffer);
                            } catch (IOException e) {
                                System.out.println(Thread.currentThread().getName()+"----读异常---取消key");
                                selectionKey.cancel();
                            }

                            byteBuffer.flip();//切换读模式
                            byte[] byteResult = new byte[byteBuffer.limit()];
                            for (int i=0;i<byteBuffer.limit();i++){
                                byteResult[i] = byteBuffer.get();
                            }
                            String data = new String(byteResult, StandardCharsets.UTF_8);
                            System.out.println(Thread.currentThread().getName()+"------收到的数据："+data);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
